#!/bin/sh
. /etc/rc.subr

name=aria2b
rcvar=aria2b_enable

start_cmd="${name}_start"
stop_cmd="${name}_stop"

load_rc_config $name
eval "${rcvar}=\${${rcvar}:-'NO'}"


CMD_PATH="/usr/local/bin/python3.6"
MAP_PID="/var/run/aria2b.pid"
MAP_LOG="/dev/null"
#MAP_LOG="/var/log/aria2b.log"


check_status()
{
	PID=`cat ${MAP_PID}`
	if [ "$PID" = "" ]; then
 		return 0
	fi
	return ${PID}
}

aria2b_start()
{
	check_status
    PID=$?
    [ "$PID" -ne 0 ] && echo "!!no:server is upping" && exit
    ${CMD_PATH} /media/conf/aria2b/main.py 1>${MAP_LOG} 2>&1 &
    echo $! > ${MAP_PID} && echo "ok:server is up"
}
aria2b_stop()
{
    check_status
    PID=$?
    [ "$PID" -eq 0 ] && echo "!!no:server don't up" &&  exit
    if [ "$PID" -ne 0 ]; then
        ps -p  ${PID}
        if [ $? -eq 0 ]; then
            kill ${PID} && `: > ${MAP_PID}` && echo "yes:server is down"
        else
            `: > ${MAP_PID}` && echo "yes:server is down"
        fi
    fi
}

run_rc_command "$1"